package com.channel.temperature.collect.app.bleupdate;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Vibrator;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;

import com.channel.temperature.collect.R;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class OTA_Uart_Active extends AppCompatActivity {

    public static final String TAG = "SYD OTA";

    private BleService bleService = null;

    String m_dir = Environment.getExternalStorageDirectory().getPath();

    private Button Exit_button;
    private Button About_button;
    private TextView Status_textView;
    private TextView MAC_textView;
    private TextView StatusPercentage_textView;
    private TextView elapsedtimer_textView;
    private TextView Update_textView;
    private TextView OTA_Bin_BirVer;
    private TextView Target_BirVer;
    ListView listview;
    private List<String> FileNameList = new ArrayList<String>();  //结果 List

    private ProgressBar mprogressBarOta;

    private String DeviceMac = null;
    private String DeviceName = null;
    private boolean isDoorOpen;

    byte[] OTABinBirthdayVer = new byte[14];

    private String OTA_FilePath = null;
    byte[] ReadData = null;
    private int SendPacketID = 0;
    private int SendPacketAllNum = 0;
    private int SendSectionID = 0;
    private int LastPacketByte = 0;
    int CRC = 0;
    byte Xor = 0;
    int SECTION_CRC = 0;

    final byte CMD_FW_WRITE_START = 0x14;
    final byte CMD_FW_UPGRADEV20 = 0x15;
    final byte CMD_FW_ERASE = 0x16;
    final byte CMD_FW_WRITE = 0x17;
    final byte ERR_COMMAND_FAILED = 0x01;
    final byte EVT_COMMAND_COMPLETE = (0x0E);

    final int MAX_TRANS_COUNT = 15;
    final int MAX_TRANS_COUNT_V30 = 20;
    final int MAX_TRANS_SECTIONALL_COUNT = 5120;
    final int MAX_TRANS_SECTIONALL_PACKET_COUNT = MAX_TRANS_SECTIONALL_COUNT / 20;
    private int MAX_TRANS_SECTIONALL_SIZE = 0;

    private boolean spinner_ReadorNot = false;

    private int actionType = 0;
    final byte ACTIONTYPE_CMD_FW_WRITE_START = 0x01;
    final byte ACTIONTYPE_CMD_FW_WRITE_END = 0x02;
    final byte ACTIONTYPE_CMD_FW_ERASE = 0x03;
    final byte ACTIONTYPE_CMD_FW_WRITE = 0x04;
    final byte ACTIONTYPE_CMD_FW_UPGRADE = 0x05;
    final byte ACTIONTYPE_CMD_FW_FINISH = 0x09;
    final byte ACTIONTYPE_CMD_TR_WRITE = 0x20;
    final byte TR_WriteQR_Bin_cmd = (byte) 0xF0;            //BLE写二维码指令

    private boolean QRType = true;
    private long uart_start_time = 0;
    final int QRDefaultAddr = 0xC4000;
    private static int key = 0;
    public static byte[] keyDefault = {0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08};

    private long oat_start_time = 0;

    public static String GMBinNAME = "TZAGMCD";
    public static String DGSBinNAME = "TZ8DGSBLMB";
    public static String TZBUPSCMB = "TZBUPSCMB";
    public static String TPM = "TPM";
    //    public static String TZBUPSEMB = "TZBUPSEMB";
    public static String TZBUPSEMB = "TZCT";
    public static byte[] Restore_table =
            {
                    (byte) 0x00, (byte) 0x5e, (byte) 0xbc, (byte) 0xe2, (byte) 0x61, (byte) 0x3f, (byte) 0xdd, (byte) 0x83, (byte) 0xc2, (byte) 0x9c, (byte) 0x7e, (byte) 0x20, (byte) 0xa3, (byte) 0xfd, (byte) 0x1f, (byte) 0x41,
                    (byte) 0x9d, (byte) 0xc3, (byte) 0x21, (byte) 0x7f, (byte) 0xfc, (byte) 0xa2, (byte) 0x40, (byte) 0x1e, (byte) 0x5f, (byte) 0x01, (byte) 0xe3, (byte) 0xbd, (byte) 0x3e, (byte) 0x60, (byte) 0x82, (byte) 0xdc,
                    (byte) 0x23, (byte) 0x7d, (byte) 0x9f, (byte) 0xc1, (byte) 0x42, (byte) 0x1c, (byte) 0xfe, (byte) 0xa0, (byte) 0xe1, (byte) 0xbf, (byte) 0x5d, (byte) 0x03, (byte) 0x80, (byte) 0xde, (byte) 0x3c, (byte) 0x62,
                    (byte) 0xbe, (byte) 0xe0, (byte) 0x02, (byte) 0x5c, (byte) 0xdf, (byte) 0x81, (byte) 0x63, (byte) 0x3d, (byte) 0x7c, (byte) 0x22, (byte) 0xc0, (byte) 0x9e, (byte) 0x1d, (byte) 0x43, (byte) 0xa1, (byte) 0xff,
                    (byte) 0x46, (byte) 0x18, (byte) 0xfa, (byte) 0xa4, (byte) 0x27, (byte) 0x79, (byte) 0x9b, (byte) 0xc5, (byte) 0x84, (byte) 0xda, (byte) 0x38, (byte) 0x66, (byte) 0xe5, (byte) 0xbb, (byte) 0x59, (byte) 0x07,
                    (byte) 0xdb, (byte) 0x85, (byte) 0x67, (byte) 0x39, (byte) 0xba, (byte) 0xe4, (byte) 0x06, (byte) 0x58, (byte) 0x19, (byte) 0x47, (byte) 0xa5, (byte) 0xfb, (byte) 0x78, (byte) 0x26, (byte) 0xc4, (byte) 0x9a,
                    (byte) 0x65, (byte) 0x3b, (byte) 0xd9, (byte) 0x87, (byte) 0x04, (byte) 0x5a, (byte) 0xb8, (byte) 0xe6, (byte) 0xa7, (byte) 0xf9, (byte) 0x1b, (byte) 0x45, (byte) 0xc6, (byte) 0x98, (byte) 0x7a, (byte) 0x24,
                    (byte) 0xf8, (byte) 0xa6, (byte) 0x44, (byte) 0x1a, (byte) 0x99, (byte) 0xc7, (byte) 0x25, (byte) 0x7b, (byte) 0x3a, (byte) 0x64, (byte) 0x86, (byte) 0xd8, (byte) 0x5b, (byte) 0x05, (byte) 0xe7, (byte) 0xb9,
                    (byte) 0x8c, (byte) 0xd2, (byte) 0x30, (byte) 0x6e, (byte) 0xed, (byte) 0xb3, (byte) 0x51, (byte) 0x0f, (byte) 0x4e, (byte) 0x10, (byte) 0xf2, (byte) 0xac, (byte) 0x2f, (byte) 0x71, (byte) 0x93, (byte) 0xcd,
                    (byte) 0x11, (byte) 0x4f, (byte) 0xad, (byte) 0xf3, (byte) 0x70, (byte) 0x2e, (byte) 0xcc, (byte) 0x92, (byte) 0xd3, (byte) 0x8d, (byte) 0x6f, (byte) 0x31, (byte) 0xb2, (byte) 0xec, (byte) 0x0e, (byte) 0x50,
                    (byte) 0xaf, (byte) 0xf1, (byte) 0x13, (byte) 0x4d, (byte) 0xce, (byte) 0x90, (byte) 0x72, (byte) 0x2c, (byte) 0x6d, (byte) 0x33, (byte) 0xd1, (byte) 0x8f, (byte) 0x0c, (byte) 0x52, (byte) 0xb0, (byte) 0xee,
                    (byte) 0x32, (byte) 0x6c, (byte) 0x8e, (byte) 0xd0, (byte) 0x53, (byte) 0x0d, (byte) 0xef, (byte) 0xb1, (byte) 0xf0, (byte) 0xae, (byte) 0x4c, (byte) 0x12, (byte) 0x91, (byte) 0xcf, (byte) 0x2d, (byte) 0x73,
                    (byte) 0xca, (byte) 0x94, (byte) 0x76, (byte) 0x28, (byte) 0xab, (byte) 0xf5, (byte) 0x17, (byte) 0x49, (byte) 0x08, (byte) 0x56, (byte) 0xb4, (byte) 0xea, (byte) 0x69, (byte) 0x37, (byte) 0xd5, (byte) 0x8b,
                    (byte) 0x57, (byte) 0x09, (byte) 0xeb, (byte) 0xb5, (byte) 0x36, (byte) 0x68, (byte) 0x8a, (byte) 0xd4, (byte) 0x95, (byte) 0xcb, (byte) 0x29, (byte) 0x77, (byte) 0xf4, (byte) 0xaa, (byte) 0x48, (byte) 0x16,
                    (byte) 0xe9, (byte) 0xb7, (byte) 0x55, (byte) 0x0b, (byte) 0x88, (byte) 0xd6, (byte) 0x34, (byte) 0x6a, (byte) 0x2b, (byte) 0x75, (byte) 0x97, (byte) 0xc9, (byte) 0x4a, (byte) 0x14, (byte) 0xf6, (byte) 0xa8,
                    (byte) 0x74, (byte) 0x2a, (byte) 0xc8, (byte) 0x96, (byte) 0x15, (byte) 0x4b, (byte) 0xa9, (byte) 0xf7, (byte) 0xb6, (byte) 0xe8, (byte) 0x0a, (byte) 0x54, (byte) 0xd7, (byte) 0x89, (byte) 0x6b, (byte) 0x35,
            };

    public static byte[] Swap_table =
            {
                    (byte) 0x00, (byte) 0x19, (byte) 0x32, (byte) 0x2b, (byte) 0x64, (byte) 0x7d, (byte) 0x56, (byte) 0x4f, (byte) 0xc8, (byte) 0xd1, (byte) 0xfa, (byte) 0xe3, (byte) 0xac, (byte) 0xb5, (byte) 0x9e, (byte) 0x87,
                    (byte) 0x89, (byte) 0x90, (byte) 0xbb, (byte) 0xa2, (byte) 0xed, (byte) 0xf4, (byte) 0xdf, (byte) 0xc6, (byte) 0x41, (byte) 0x58, (byte) 0x73, (byte) 0x6a, (byte) 0x25, (byte) 0x3c, (byte) 0x17, (byte) 0x0e,
                    (byte) 0x0b, (byte) 0x12, (byte) 0x39, (byte) 0x20, (byte) 0x6f, (byte) 0x76, (byte) 0x5d, (byte) 0x44, (byte) 0xc3, (byte) 0xda, (byte) 0xf1, (byte) 0xe8, (byte) 0xa7, (byte) 0xbe, (byte) 0x95, (byte) 0x8c,
                    (byte) 0x82, (byte) 0x9b, (byte) 0xb0, (byte) 0xa9, (byte) 0xe6, (byte) 0xff, (byte) 0xd4, (byte) 0xcd, (byte) 0x4a, (byte) 0x53, (byte) 0x78, (byte) 0x61, (byte) 0x2e, (byte) 0x37, (byte) 0x1c, (byte) 0x05,
                    (byte) 0x16, (byte) 0x0f, (byte) 0x24, (byte) 0x3d, (byte) 0x72, (byte) 0x6b, (byte) 0x40, (byte) 0x59, (byte) 0xde, (byte) 0xc7, (byte) 0xec, (byte) 0xf5, (byte) 0xba, (byte) 0xa3, (byte) 0x88, (byte) 0x91,
                    (byte) 0x9f, (byte) 0x86, (byte) 0xad, (byte) 0xb4, (byte) 0xfb, (byte) 0xe2, (byte) 0xc9, (byte) 0xd0, (byte) 0x57, (byte) 0x4e, (byte) 0x65, (byte) 0x7c, (byte) 0x33, (byte) 0x2a, (byte) 0x01, (byte) 0x18,
                    (byte) 0x1d, (byte) 0x04, (byte) 0x2f, (byte) 0x36, (byte) 0x79, (byte) 0x60, (byte) 0x4b, (byte) 0x52, (byte) 0xd5, (byte) 0xcc, (byte) 0xe7, (byte) 0xfe, (byte) 0xb1, (byte) 0xa8, (byte) 0x83, (byte) 0x9a,
                    (byte) 0x94, (byte) 0x8d, (byte) 0xa6, (byte) 0xbf, (byte) 0xf0, (byte) 0xe9, (byte) 0xc2, (byte) 0xdb, (byte) 0x5c, (byte) 0x45, (byte) 0x6e, (byte) 0x77, (byte) 0x38, (byte) 0x21, (byte) 0x0a, (byte) 0x13,
                    (byte) 0x2c, (byte) 0x35, (byte) 0x1e, (byte) 0x07, (byte) 0x48, (byte) 0x51, (byte) 0x7a, (byte) 0x63, (byte) 0xe4, (byte) 0xfd, (byte) 0xd6, (byte) 0xcf, (byte) 0x80, (byte) 0x99, (byte) 0xb2, (byte) 0xab,
                    (byte) 0xa5, (byte) 0xbc, (byte) 0x97, (byte) 0x8e, (byte) 0xc1, (byte) 0xd8, (byte) 0xf3, (byte) 0xea, (byte) 0x6d, (byte) 0x74, (byte) 0x5f, (byte) 0x46, (byte) 0x09, (byte) 0x10, (byte) 0x3b, (byte) 0x22,
                    (byte) 0x27, (byte) 0x3e, (byte) 0x15, (byte) 0x0c, (byte) 0x43, (byte) 0x5a, (byte) 0x71, (byte) 0x68, (byte) 0xef, (byte) 0xf6, (byte) 0xdd, (byte) 0xc4, (byte) 0x8b, (byte) 0x92, (byte) 0xb9, (byte) 0xa0,
                    (byte) 0xae, (byte) 0xb7, (byte) 0x9c, (byte) 0x85, (byte) 0xca, (byte) 0xd3, (byte) 0xf8, (byte) 0xe1, (byte) 0x66, (byte) 0x7f, (byte) 0x54, (byte) 0x4d, (byte) 0x02, (byte) 0x1b, (byte) 0x30, (byte) 0x29,
                    (byte) 0x3a, (byte) 0x23, (byte) 0x08, (byte) 0x11, (byte) 0x5e, (byte) 0x47, (byte) 0x6c, (byte) 0x75, (byte) 0xf2, (byte) 0xeb, (byte) 0xc0, (byte) 0xd9, (byte) 0x96, (byte) 0x8f, (byte) 0xa4, (byte) 0xbd,
                    (byte) 0xb3, (byte) 0xaa, (byte) 0x81, (byte) 0x98, (byte) 0xd7, (byte) 0xce, (byte) 0xe5, (byte) 0xfc, (byte) 0x7b, (byte) 0x62, (byte) 0x49, (byte) 0x50, (byte) 0x1f, (byte) 0x06, (byte) 0x2d, (byte) 0x34,
                    (byte) 0x31, (byte) 0x28, (byte) 0x03, (byte) 0x1a, (byte) 0x55, (byte) 0x4c, (byte) 0x67, (byte) 0x7e, (byte) 0xf9, (byte) 0xe0, (byte) 0xcb, (byte) 0xd2, (byte) 0x9d, (byte) 0x84, (byte) 0xaf, (byte) 0xb6,
                    (byte) 0xb8, (byte) 0xa1, (byte) 0x8a, (byte) 0x93, (byte) 0xdc, (byte) 0xc5, (byte) 0xee, (byte) 0xf7, (byte) 0x70, (byte) 0x69, (byte) 0x42, (byte) 0x5b, (byte) 0x14, (byte) 0x0d, (byte) 0x26, (byte) 0x3f,
            };
    boolean isupdating = false;
    private final BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (BleService.GATT_CONNECTED.equals(action)) {
                ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.device_connected));
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                bleService.GetInfData();
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (isupdating == false) {
                    isupdating = true;
                    startupdate();
                }


            } else if (BleService.ACTION_DATA_INFREAD.equals(action)) {
                Log.i("SYD_OTA", "ACTION_DATA_INFREAD");
                byte[] data = intent.getByteArrayExtra("data");
                String ShowTarget_BirVer = new String(data);
                ShowTarget_BirVer(OTA_Uart_Active.this.getResources().getString(R.string.board_information) + "   【" + ShowTarget_BirVer + "】");
            } else if (BleService.GATT_DISCONNECTED.equals(action)) {
                OTA_Uart_Process_init();
            } else if (BleService.ACTION_RSSI_READ.equals(action)) {
                String data = intent.getStringExtra("value");
//              updateDeviceRssi(data);
            } else if (BleService.ACTION_DATA_UartWRITE.equals(action)) {
                bleService.receiveUartData();
//                try {
//                    Thread.sleep(20);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
            } else if (BleService.ACTION_DATA_UartNOTIFY.equals(action)) {
                int status = intent.getIntExtra("value", 0);
                byte[] data = intent.getByteArrayExtra("data");
                UART_Process_doing(status, data);
            } else if (BleService.ACTION_DATA_WRITE.equals(action)) {
                int status = intent.getIntExtra("value", 0);
                byte[] data = intent.getByteArrayExtra("data");
                //是否去读
                if (spinner_ReadorNot == false) {
                    Log.i("SYD_OTA", "Send PacketID:" + SendPacketID + "  AllNum:" + SendPacketAllNum);
                    OTA_Process_doing(status, data);
                } else {
                    Log.i("SYD_OTA", "Receive PacketID:" + SendPacketID + "  AllNum:" + SendPacketAllNum);
                    bleService.receiveData();
                }
            } else if (BleService.ACTION_DATA_READ.equals(action)) {
                Log.i("SYD_OTA", "ACTION_DATA_READ");
                if (spinner_ReadorNot == true) {
                    int status = intent.getIntExtra("value", 0);
                    byte[] data = intent.getByteArrayExtra("data");
                    OTA_Process_doing(status, data);
                }
            }
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BleService.GATT_CONNECTED);
        intentFilter.addAction(BleService.GATT_DISCONNECTED);
        intentFilter.addAction(BleService.GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(BleService.ACTION_DATA_CHANGE);
        intentFilter.addAction(BleService.ACTION_DATA_READ);
        intentFilter.addAction(BleService.ACTION_DATA_WRITE);
        intentFilter.addAction(BleService.ACTION_RSSI_READ);
        intentFilter.addAction(BleService.ACTION_DATA_UartWRITE);
        intentFilter.addAction(BleService.ACTION_DATA_UartNOTIFY);
        intentFilter.addAction(BleService.ACTION_DATA_INFREAD);
        return intentFilter;
    }

    private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i("SYD_OTA", "DisplayCtrl service onServiceConnected");
            bleService = ((BleService.LoadcalBinder) service).getService();

            if (!bleService.BlutoothConnectStatue) {
                if (DeviceMac != null) {
                    bleService.connectDevice(DeviceMac);
                    ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.device_connecting));
                } else {
                    ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.device_unselected));
                }
            } else {
                ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.device_connected));
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i("SYD_OTA", "service onServiceDisconnected");
        }
    };

    int versionCode = 0;
    int binFileType;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main_ble_update);

        Intent intent = getIntent();
        DeviceMac = intent.getStringExtra("DEVICE_MAC");
        DeviceName = intent.getStringExtra("DEVICE_NAME");
        versionCode = intent.getIntExtra("version", 0);
        binFileType = intent.getIntExtra("binType", 1);
        Log.e("DeviceName", " DeviceName :" + DeviceName);
        if (DeviceName.contains("ISC")) {
            isDoorOpen = true;
        } else {
            isDoorOpen = intent.getBooleanExtra("isDoorOpenTR", false);
        }


        Exit_button = (Button) findViewById(R.id.Exit_button);

        Status_textView = (TextView) findViewById(R.id.Status_textView);
        StatusPercentage_textView = (TextView) findViewById(R.id.StatusPercentage_textView);
        elapsedtimer_textView = (TextView) findViewById(R.id.elapsedtimer_textView);
        Update_textView = (TextView) findViewById(R.id.Update_textView);
        OTA_Bin_BirVer = (TextView) findViewById(R.id.OTA_Bin_BirVer);
        Target_BirVer = (TextView) findViewById(R.id.Target_BirVer);
        listview = (ListView) findViewById(R.id.f_name);
        MAC_textView = (TextView) findViewById(R.id.MAC_textView);

        MAC_textView.setText("MAC:" + DeviceMac);

        intent = new Intent(this, BleService.class);
        registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        boolean a = bindService(intent, serviceConnection, BIND_AUTO_CREATE);
        Log.i("SYD_OTA", "onCreate bindService end:" + a);

        SharedPreferences sPreferences = getSharedPreferences("svae_config", MODE_PRIVATE);
        mprogressBarOta = (ProgressBar) findViewById(R.id.progressBarOta);

        GetFiles(m_dir, ".bin");
        ArrayAdapter<String> array = new ArrayAdapter(OTA_Uart_Active.this, android.R.layout.simple_list_item_1, FileNameList);
        listview.setAdapter(array);
//        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                RxPermissions permissions = new RxPermissions(OTA_Uart_Active.this);
//                permissions.setLogging(true);
//                permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                        .subscribe(new Consumer<Boolean>() {
//                            @Override
//                            public void accept(Boolean aBoolean) throws Exception {
//                                if (aBoolean) {
//                                    Toast.makeText(OTA_Uart_Active.this, "选择:" + FileNameList.get(i) + "文件,开始传送，耐心等待!!!", Toast.LENGTH_SHORT).show();
//                                    OTA_FilePath = m_dir + File.separator + FileNameList.get(i);
//                                    Log.e("OTA_FilePath", "OTA_FilePath  : " + OTA_FilePath);
//                                    File file = new File(OTA_FilePath);
//                                    Log.e("OTA_FilePath", "11111111111111 : " + file.getName() + "   , " + file.length());
//                                    ShowUpdatefile("已选文件: " + FileNameList.get(i) + " " + Long.toString(file.length() / 1000) + "." + Long.toString(file.length() % 1000) + "Kbyte/S");
//
////                if (CheckBinFileType() == QRType) {//二维码文件
////                    uart_start_time = System.currentTimeMillis();
////                    Uart_Process_Start();
////                } else {
////                    if (isDoorOpen == false) {
////                        ShowUpdatefile("请解锁后再升级！");
////                        Toast.makeText(OTA_Uart_Active.this, "请解锁后再升级", Toast.LENGTH_SHORT).show();
////                        return;
////                    }
//                                    if (CheckOTABinaryFile() == false) {
//                                        ShowUpdatefile("非法文件！");
//                                        Toast.makeText(OTA_Uart_Active.this, "文件错误", Toast.LENGTH_SHORT).show();
//                                        return;
//                                    }
////                    if (file.length() < 1024) {
////                        Toast.makeText(OTA_Uart_Active.this, "文件太小，请重新选择！", Toast.LENGTH_SHORT).show();
////                        ShowUpdatefile("文件错误！" + FileNameList.get(i) + " " + Long.toString(file.length() / 1000) + "." + Long.toString(file.length() % 1000) + "Kbyte");
////                        return;
////                    }
////
//                                    oat_start_time = System.currentTimeMillis();
//                                    OTA_Process_Start();
//                                    String ShowOTABinBirthdayVer = new String(OTABinBirthdayVer);
//                                    ShowOTA_Bin_BirVer("OTA Bin信息: 【" + ShowOTABinBirthdayVer + "】");
//                                    Target_BirVer.setText("当前版本: V00" + versionCode);
////                }
//                                }
//                            }
//                        });
//
//
//            }
//        });
        Exit_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
            }
        });
    }


    public void startupdate() {
//        Observable.timer(1000, TimeUnit.MILLISECONDS)
//                .subscribe(new Action1<Long>() {
//                    @Override
//                    public void call(Long aLong) {
//                        //检查是否有自动登录
//                        if (MySharedCache.get(Constant.AUTO_LOGIN, false)) {
//                            Log.e("autoLoginByToken", "自动登录");
//                        } else {
//                            Intent intent = new Intent(OTA_Uart_Active.this, LoginActivity.class);
//                            startActivity(intent);
//                            finish();
//                        }
//                    }
//                });

//        RxPermissions permissions = new RxPermissions(OTA_Uart_Active.this);
//        permissions.setLogging(true);
//        permissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
//                .subscribe(new Consumer<Boolean>() {
//                    @Override
//                    public void accept(Boolean aBoolean) throws Exception {
//                        if (aBoolean) {
        Toast.makeText(OTA_Uart_Active.this, OTA_Uart_Active.this.getResources().getString(R.string.choose_tips)
                + FileNameList.get(0) + OTA_Uart_Active.this.getResources().getString(R.string.waiting_tips), Toast.LENGTH_SHORT).show();
        OTA_FilePath = m_dir + File.separator + FileNameList.get(0);
        Log.e("OTA_FilePath", "OTA_FilePath  : " + OTA_FilePath);

        File file = new File(OTA_FilePath);
        Log.e("OTA_FilePath", "11111111111111 : " + file.getName() + "   , " + file.length());
        ShowUpdatefile("");

//                if (CheckBinFileType() == QRType) {//二维码文件
//                    uart_start_time = System.currentTimeMillis();
//                    Uart_Process_Start();
//                } else {
//                    if (isDoorOpen == false) {
//                        ShowUpdatefile("请解锁后再升级！");
//                        Toast.makeText(OTA_Uart_Active.this, "请解锁后再升级", Toast.LENGTH_SHORT).show();
//                        return;
//                    }
        if (CheckOTABinaryFile() == false) {
            ShowUpdatefile(OTA_Uart_Active.this.getResources().getString(R.string.illegal_file));
            Toast.makeText(OTA_Uart_Active.this, OTA_Uart_Active.this.getResources().getString(R.string.file_error), Toast.LENGTH_SHORT).show();
            return;
        }
//                    if (file.length() < 1024) {
//                        Toast.makeText(OTA_Uart_Active.this, "文件太小，请重新选择！", Toast.LENGTH_SHORT).show();
//                        ShowUpdatefile("文件错误！" + FileNameList.get(i) + " " + Long.toString(file.length() / 1000) + "." + Long.toString(file.length() % 1000) + "Kbyte");
//                        return;
//                    }
//
        oat_start_time = System.currentTimeMillis();
        OTA_Process_Start();
        String ShowOTABinBirthdayVer = new String(OTABinBirthdayVer);
        ShowOTA_Bin_BirVer(OTA_Uart_Active.this.getResources().getString(R.string.ota_bin_info) + " 【" + ShowOTABinBirthdayVer + "】");
        Target_BirVer.setText(OTA_Uart_Active.this.getResources().getString(R.string.current_version_v) + versionCode);
//                }
//                        }
//                    }
//                });
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
//            bleService.disconnectDevice();
//
//            // 获取启动当前Activity的上一个Intent
//            Intent intent = new Intent(OTA_Uart_Active.this,
//                    ScanBLEActivity.class);
//            // 启动intent对应的Activity
//            startActivity(intent);
//
//            finish();
//            // 结束当前Activity
//            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onStart() {
        super.onStart();
    }

    void OTA_Uart_Process_init() {
        SendPacketID = 0;
        SendPacketAllNum = 0;
        OTA_FilePath = null;
        CRC = 0;
        ReadData = null;
        actionType = 0;
        SendSectionID = 0;
        SECTION_CRC = 0;
        MAX_TRANS_SECTIONALL_SIZE = 0;
    }

    void UART_Process_doing(int status, final byte[] data) {

        if (actionType == ACTIONTYPE_CMD_TR_WRITE) {
            int RecPacketID = (data[3] << 8) + (data[2] & 0xFF);
            if (data[4] == (byte) 0x5A) {
                SendPacketID = RecPacketID + 1;
                if ((SendPacketID << 4) >= SendPacketAllNum) {
                    ShowStatusPercentage("100.00%");
                    ShowProgressBar((int) (float) 100);

                    ShowStatus("二维码文件下载完成……");
                    ShowVibrator((byte) 0);
                    EnableListview(listview, true);
                    EnableButton(Exit_button, true);
                    OTA_Uart_Process_init();
                    bleService.disconnectDevice();
                } else {
                    CRC = 0;
                    NumberFormat numberFormat = NumberFormat.getInstance();
                    // 设置精确到小数点后2位
                    numberFormat.setMaximumFractionDigits(2);
                    String result = numberFormat.format((float) (SendPacketID << 4) / (float) SendPacketAllNum * 100) + "%";
                    ShowStatusPercentage(result);
                    ShowProgressBar((int) ((float) (SendPacketID << 4) / (float) SendPacketAllNum * 100));
                    TR_sendUartData_BLE();
                }
            } else if (data[4] == (byte) 0xA5) {
                ShowStatus("“字库图片下载”界面才能下载文件……");
                ShowVibrator((byte) 0);
                EnableListview(listview, true);
                EnableButton(Exit_button, true);
                OTA_Uart_Process_init();
                bleService.disconnectDevice();
            } else if (++CRC < 10) {
                Log.i("Uart_QR", SendPacketID + "/" + (SendPacketAllNum >> 4));
                TR_sendUartData_BLE();
            } else {
                ShowStatus("二维码文件下载出错, 复位设备中……");
                ShowVibrator((byte) 0);
                EnableListview(listview, true);
                EnableButton(Exit_button, true);
                OTA_Uart_Process_init();
                bleService.disconnectDevice();
            }
        }
        long uart_now_time = System.currentTimeMillis();
        Showelapsedtimer(uart_now_time - uart_start_time);
    }

    void OTA_Process_doing(int status, final byte[] data) {

        if (actionType == ACTIONTYPE_CMD_FW_ERASE) {
            Toast.makeText(this, OTA_Uart_Active.this.getResources().getString(R.string.erase_space_tips), Toast.LENGTH_LONG).show();
            new Handler().postDelayed(new Runnable() {
                public void run() {
                    //execute the task
                    OTA_Write_Flash_Start_V30(data);
                }
            }, 3000);
        } else if (actionType == ACTIONTYPE_CMD_FW_WRITE) {
            OTA_Write_All_Flash(status);
        } else if (actionType == ACTIONTYPE_CMD_FW_WRITE_START) {
            OTA_Write_Section_All_Flash(status);
        } else if (actionType == ACTIONTYPE_CMD_FW_WRITE_END) {
            OTA_Write_Flash_Continue_V30(data);
        } else if (actionType == ACTIONTYPE_CMD_FW_UPGRADE) {
            OTA_Upgrade_Flash_V30(ReadData.length, CRC);
        } else if (actionType == ACTIONTYPE_CMD_FW_FINISH) {
            if (((data[0] & 0xFF) == EVT_COMMAND_COMPLETE) && ((data[3] & 0xFF) == ERR_COMMAND_FAILED)) {
                ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_failed_tips1));
                isupdating = false;
            } else {
                ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_completed_tips));
                isupdating = false;
                ShowVibrator((byte) 0);
            }

            try {
                Thread.sleep(2100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            EnableListview(listview, true);
            EnableButton(Exit_button, true);
            OTA_Uart_Process_init();
            bleService.disconnectDevice();
        }
        long oat_now_time = System.currentTimeMillis();


        Showelapsedtimer(oat_now_time - oat_start_time);
    }

    private boolean CheckBinFileType() {
        ReadData = ReadOTAFileBinary(OTA_FilePath);
        if (ReadData.length == 0x3F48) {
            return QRType;
        }
        return false;
    }

    public static int SYMM_SWAP(byte key) {
        return ((key & 1) << 7) | ((key & 2) << 5) | ((key & 4) << 3) | ((key & 8) << 1) | ((key & 0x10) >> 1)
                | ((key & 0x20) >> 3) | ((key & 0x40) >> 5) | ((key & 0x80) >> 7);
    }

    //加密
    private byte[] Encryption(byte[] original, int start, int len) {
        for (int i = start; i < start + len; ++i) {
            original[i] = (byte) (((byte) SYMM_SWAP(original[i])) ^ ((byte) key));
        }

        original[start + len] = ((byte) key);
        return original;
    }

    public static byte colCheckByte(byte[] datamsg, int start, int len) {
        byte check = 0;
        for (int i = start; i < start + len; ++i) {
            check = ((byte) (datamsg[i] ^ check));
        }

        return check;
    }


    public void TR_sendUartData_BLE() {
        int i = 0, SendDataLen;
        byte[] WriteData = new byte[20];

        actionType = ACTIONTYPE_CMD_TR_WRITE;
        if ((SendPacketAllNum - (SendPacketID << 4)) >= 16) {
            SendDataLen = 16;
        } else {
            SendDataLen = (SendPacketAllNum - (SendPacketID << 4));
        }
        WriteData[0] = TR_WriteQR_Bin_cmd;
        WriteData[1] = (byte) (2 + SendDataLen);
        WriteData[2] = (byte) (SendPacketID & 0x000000FF);
        WriteData[3] = (byte) ((SendPacketID & 0x0000FF00) >> 8);
        for (i = 0; i < SendDataLen; i++) {
            WriteData[4 + i] = ReadData[(SendPacketID << 4) + i];
        }
        Log.i("TR_UART", "TR_sendData--------->" + bleService.bytes2String(WriteData) + "     " + SendPacketID + "/" + (SendPacketAllNum >> 4));
//        Build_BLE_TX_Pkt(WriteData);
        bleService.sendUartData(WriteData);
    }

    void Uart_Process_Start() {
        SendPacketID = 0;
        SendPacketAllNum = ReadData.length;

        EnableListview(listview, false);
        ShowStatus("请勿中断，二维码文件下载中 ...");
        TR_sendUartData_BLE();
    }

    private boolean CheckOTABinaryFile() {
        ReadData = ReadOTAFileBinary(OTA_FilePath);
        int i = 0;
        int CRCResultS = 0, CRCResultD = 0;

        Log.e("CheckOTABinaryFile", "  ReadData  " + ReadData.length);
        byte[] value = Arrays.copyOfRange(ReadData, ReadData.length - 32, ReadData.length - 32 + 10);
        Log.e("CheckOTABinaryFile", "sasasaas2222221111 " + new String(value));
        if ((new String(value).contains(TZBUPSEMB))) {
            Log.e("CheckOTABinaryFile", "sasasaas222222");
            for (i = 0; i < (ReadData.length - 32); i++) {
                CRCResultD = Restore_table[CRCResultD ^ (ReadData[i] & 0x000000FF)] & 0x000000FF;
                CRCResultS = Restore_table[(CRCResultS ^ Restore_table[ReadData[i] & 0x000000FF]) & 0x000000FF] & 0x000000FF;
            }
            if (CRCResultS != (ReadData[ReadData.length - 3] & 0x000000FF))
                return false;
            else if (CRCResultD != (ReadData[ReadData.length - 2] & 0x000000FF))
                return false;
            else
                return true;
        } else {
            Log.e("sasasaas", "sasasaas1111");
            return false;
        }
    }

    void OTA_Process_Start() {
        ReadData = ReadOTAFileBinary(OTA_FilePath);
        int i = 0;
        EnableListview(listview, false);

        System.arraycopy(ReadData, ReadData.length - 16, OTABinBirthdayVer, 0, 12);
        i = OTABinBirthdayVer[11] & 0x000000FF;
        if (i < 10) {
            OTABinBirthdayVer[11] = (byte) (0x30);
            OTABinBirthdayVer[12] = (byte) (0x30);
            OTABinBirthdayVer[13] = (byte) (0x30 + i);
        } else if (i < 100) {
            OTABinBirthdayVer[11] = (byte) (0x30);
            OTABinBirthdayVer[12] = (byte) (0x30 + i / 10);
            OTABinBirthdayVer[13] = (byte) (0x30 + i % 10);
        } else {
            OTABinBirthdayVer[11] = (byte) (0x30 + i / 100);
            OTABinBirthdayVer[12] = (byte) (0x30 + (i / 10) % 10);
            OTABinBirthdayVer[13] = (byte) (0x30 + i % 10);
        }

        for (i = ReadData.length - 32; i < (ReadData.length); i++) {
            ReadData[i] = Swap_table[ReadData[i] & 0x000000FF];
        }
        for (i = 0; i < ReadData.length; i++) {
            int CC = Restore_table[ReadData[i] & 0x000000FF];
            CC &= 0x000000FF;
            CRC += CC;
            CRC = CRC & 0x0000FFFF;
        }
        Log.i("SYD_OTA", "OTA_Process_Start CRC ==>" + CRC);

        OTA_Erase_Flash();
    }

    public void OTA_Speed_BLE() {
        byte[] WriteData = new byte[4];
        WriteData[0] = (byte) 0xFC;
        WriteData[1] = 0x01;
        WriteData[2] = 0x00;
        WriteData[3] = 0x00;

        Log.i("SYD_OTA", "OTA Speed BLE");
        bleService.sendUartData(WriteData);
    }

    public void OTA_Erase_Flash() {
        actionType = ACTIONTYPE_CMD_FW_ERASE;

        byte[] WriteData = new byte[2];
        WriteData[0] = CMD_FW_ERASE;
        WriteData[1] = 0x00;
        Log.i("SYD_OTA", "OTA_Erase_Flash Start");
        bleService.sendData(WriteData, spinner_ReadorNot);
    }

    public void OTA_Write_Flash_Start_V30(byte[] data) {
        Log.i("SYD_OTA", "OTA_Write_Flash_Start_V30");

        SendPacketAllNum = ReadData.length / MAX_TRANS_COUNT_V30;
        if (ReadData.length % MAX_TRANS_COUNT_V30 != 0)
            SendPacketAllNum += 1;


        OTA_Write_Flash_Continue_V30(data);

        // 创建一个数值格式化对象
        NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);

        String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
        ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_tips));
        ShowStatusPercentage(result);
        ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
    }

    public void OTA_Write_Flash_Continue_V30(byte[] data) {
        Log.i("SYD_OTA", "OTA_Write_Flash_Continue");
        actionType = ACTIONTYPE_CMD_FW_WRITE_START;

        Log.i("SYD_OTA", "SendSectionID ==>" + SendSectionID);

        if ((SendSectionID != 0) && (data != null)) {
            int check = ((data[7] & 0xff) << 8) | (data[6] & 0xff);

            //error check and resend
            if ((check & 0x0000ffff) != (SECTION_CRC & 0x0000ffff)) {
                Log.i("SYD_OTA", "SECTION resend:" + SendSectionID + " check device:" + check + " check app:" + SECTION_CRC);
                SendSectionID -= 1;
                SendPacketID = MAX_TRANS_SECTIONALL_PACKET_COUNT * SendSectionID;
            }
        }

        if ((SendPacketAllNum - SendPacketID) > MAX_TRANS_SECTIONALL_PACKET_COUNT)
            MAX_TRANS_SECTIONALL_SIZE = MAX_TRANS_SECTIONALL_COUNT;
        else
            MAX_TRANS_SECTIONALL_SIZE = ReadData.length % MAX_TRANS_SECTIONALL_COUNT;

        SECTION_CRC = 0;

        Log.i("SYD_OTA", "SendPacketID ==>" + SendPacketID);
        Log.i("SYD_OTA", "SendPacketAllNum ==>" + SendPacketAllNum);
        Log.i("SYD_OTA", "MAX_TRANS_SECTIONALL_PACKET_COUNT ==>" + MAX_TRANS_SECTIONALL_PACKET_COUNT);


        Log.i("SYD_OTA", "MAX_TRANS_SECTIONALL_SIZE ==>" + MAX_TRANS_SECTIONALL_SIZE);
        Log.i("SYD_OTA", "MAX_TRANS_SECTIONALL_COUNT ==>" + MAX_TRANS_SECTIONALL_COUNT);
        Log.i("SYD_OTA", "SendSectionID ==>" + SendSectionID);
        Log.i("SYD_OTA", "SendSectionID*MAX_TRANS_SECTIONALL_COUNT ==>" + SendSectionID * MAX_TRANS_SECTIONALL_COUNT);


        Log.i("SYD_OTA", "ReadData.length ==>" + ReadData.length);

        for (int i = 0; i < MAX_TRANS_SECTIONALL_SIZE; i++) {
            int CC = ReadData[SendSectionID * MAX_TRANS_SECTIONALL_COUNT + i];
            CC &= 0x000000FF;
            SECTION_CRC += CC;
        }

        Log.i("SYD_OTA", "SECTION_CRC ==>" + SECTION_CRC);
        OTA_Write_Flash_section_start(SECTION_CRC, MAX_TRANS_SECTIONALL_SIZE, SendSectionID);
        SendSectionID += 1;

        spinner_ReadorNot = false;
    }

    public void OTA_Write_All_Flash(int status) {
        int srcPos = SendPacketID * MAX_TRANS_COUNT;

        final byte[] dataPacket = new byte[MAX_TRANS_COUNT];
        if (status == 0) {
            if (SendPacketID == SendPacketAllNum) {
                actionType = 0;
            } else {
                if (SendPacketID == (SendPacketAllNum - 1)) {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, (ReadData.length - srcPos));//last a packet
                    actionType = ACTIONTYPE_CMD_FW_UPGRADE;//发送完最后一包了
                } else {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, MAX_TRANS_COUNT);//other packet except first and last packet
                }
                OTA_Write_Flash(dataPacket, SendPacketID);
                SendPacketID += 1;
            }
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
            ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_tips));
            ShowStatusPercentage(result);
            ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
        } else {
            ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_falied_retry_tips));
        }
    }

    public void OTA_Write_Section_All_Flash(int status) {

        int srcPos = SendPacketID * MAX_TRANS_COUNT_V30;
        final byte[] dataPacket = new byte[MAX_TRANS_COUNT_V30];
        if (status == 0) {

            Log.i("SYD_OTA", "SendPacketID ==>" + SendPacketID);
            Log.i("SYD_OTA", "MAX_TRANS_COUNT_V30 ==>" + MAX_TRANS_COUNT_V30);
            Log.i("SYD_OTA", "srcPos ==>" + srcPos);
            Log.i("SYD_OTA", "SendPacketAllNum ==>" + SendPacketAllNum);


            if (SendPacketID == SendPacketAllNum) {
                actionType = 0;
            } else {
                if (SendPacketID == (SendPacketAllNum - 1)) {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, (ReadData.length - srcPos));//last a packet
                    actionType = ACTIONTYPE_CMD_FW_UPGRADE;//发送完最后一包了
                } else {
                    System.arraycopy(ReadData, srcPos, dataPacket, 0, MAX_TRANS_COUNT_V30);//other packet except first and last packet
                }
                OTA_Write_Secton_Flash(dataPacket, SendPacketID);
                SendPacketID += 1;
            }
            Log.i("SYD_OTA", "SendPacketID%MAX_TRANS_SECTIONALL_PACKET_COUNT ==>" + SendPacketID % MAX_TRANS_SECTIONALL_PACKET_COUNT);

            if (actionType != ACTIONTYPE_CMD_FW_UPGRADE) {
                if (SendPacketID % MAX_TRANS_SECTIONALL_PACKET_COUNT == 0) {
                    actionType = ACTIONTYPE_CMD_FW_WRITE_END;
                    spinner_ReadorNot = true;
                    Log.i("SYD_OTA", "Section:" + Integer.toString(SendPacketID / MAX_TRANS_SECTIONALL_PACKET_COUNT));
                }
            }
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String result = numberFormat.format((float) SendPacketID / (float) SendPacketAllNum * 100) + "%";
            ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_tips));
            ShowStatusPercentage(result);
            ShowProgressBar((int) ((float) SendPacketID / (float) SendPacketAllNum * 100));
        } else {
            ShowStatus(OTA_Uart_Active.this.getResources().getString(R.string.ota_falied_retry_tips));
        }
    }

    public void OTA_Write_Flash(byte[] ProgramData, int Address) {
        byte[] WriteData = new byte[20];
        Address = Address * MAX_TRANS_COUNT;

        WriteData[0] = CMD_FW_WRITE;
        WriteData[1] = 0x13;
        WriteData[2] = (byte) (Address & 0x000000FF);
        WriteData[3] = (byte) ((Address & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ProgramData.length;

        int i = 0;
        for (i = 0; i < ProgramData.length; i++) {
            WriteData[i + 5] = ProgramData[i];
        }
        Log.i("SYD_OTA", "OTA_Write_Flash");
        Log.i("SYD_OTA", "spinner_ReadorNot--->" + spinner_ReadorNot);
        bleService.sendData(WriteData, spinner_ReadorNot);//写入第一包
    }

    public void OTA_Write_Secton_Flash(byte[] ProgramData, int Address) {
        bleService.sendData(ProgramData, spinner_ReadorNot, BluetoothGattCharacteristic.WRITE_TYPE_NO_RESPONSE);//写入第一包
    }

    public void OTA_Write_Flash_section_start(int check, int size, int Address) {
        byte[] WriteData = new byte[14];
        Address = Address * MAX_TRANS_SECTIONALL_COUNT;

        WriteData[0] = CMD_FW_WRITE_START;
        WriteData[1] = 0x13;
        WriteData[2] = (byte) (Address & 0x000000FF);
        WriteData[3] = (byte) ((Address & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ((Address & 0x00FF0000) >> 16);
        WriteData[5] = (byte) ((Address & 0xFF000000) >> 24);
        WriteData[6] = (byte) (size & 0x000000FF);
        WriteData[7] = (byte) ((size & 0x0000FF00) >> 8);
        WriteData[8] = (byte) (check & 0x000000FF);
        WriteData[9] = (byte) ((check & 0x0000FF00) >> 8);
        WriteData[10] = (byte) (SendPacketID & 0x000000FF);
        WriteData[11] = (byte) ((SendPacketID & 0x0000FF00) >> 8);
        WriteData[12] = (byte) (SendPacketAllNum & 0x000000FF);
        WriteData[13] = (byte) ((SendPacketAllNum & 0x0000FF00) >> 8);

        bleService.sendData(WriteData, spinner_ReadorNot);//写入第一包
    }

    public void OTA_Upgrade_Flash_V30(int Size, int CRC) {
        Log.i("SYD_OTA", "OTA_Upgrade_Flash CRC_V30:" + CRC + "Size" + Size);
        byte[] WriteData = new byte[MAX_TRANS_COUNT_V30];

        WriteData[0] = CMD_FW_UPGRADEV20;
        WriteData[1] = 0x04;
        WriteData[2] = (byte) (Size & 0x000000FF);
        WriteData[3] = (byte) ((Size & 0x0000FF00) >> 8);
        WriteData[4] = (byte) ((Size & 0x00FF0000) >> 16);
        WriteData[5] = (byte) ((Size & 0xFF000000) >> 24);
        WriteData[6] = (byte) (CRC & 0x000000FF);
        WriteData[7] = (byte) ((CRC & 0x0000FF00) >> 8);
        System.arraycopy(ReadData, ReadData.length - 16, WriteData, 8, 12);//last a packet
        actionType = ACTIONTYPE_CMD_FW_FINISH;
        spinner_ReadorNot = true;
        bleService.sendData(WriteData, spinner_ReadorNot);
    }

    byte[] ReadOTAFileBinary(String filepath) {
        Log.e("CheckOTABinaryFile", "CheckOTABinaryFile : " + filepath);
        File file = new File(filepath);
        Log.e("CheckOTABinaryFile", "CheckOTABinaryFile 111111: " + file.length());
        try {
//            FileInputStream fis = new FileInputStream(file);

//            InputStream fis = getResources().openRawResource(R.raw.tzbupsemb_tpm_22_12_20_v005);
//            InputStream fis;
//            fis = getResources().openRawResource(R.raw.tc);
            InputStream fis;
            if (binFileType == 1) {
                fis = getResources().openRawResource(R.raw.tc10);
            } else if (binFileType == 2) {
                fis = getResources().openRawResource(R.raw.tc11);
            } else {
                fis = getResources().openRawResource(R.raw.tc11);
            }
            int length = fis.available();
            byte[] BinaryData = new byte[length];

            fis.read(BinaryData);

            fis.close();
            Log.e("CheckOTABinaryFile", "你选的是第" + binFileType + "个bin文件, " + "  ReadData ReadOTAFileBinary" + BinaryData.length);
//            ToastUtils.showShort("你选的是第" + binFileType + "个bin文件, " + BinaryData.length);
            return BinaryData;
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        byte[] BinaryData = new byte[]{0x01, 0x01};
        Log.e("CheckOTABinaryFile", "  ReadData ReadOTAFileBinary" + BinaryData.length);
        return BinaryData;
    }

    //搜索目录，扩展名
    public void GetFiles(String Path, String Extension) {
//        File[] files = new File(Path).listFiles();//获取文件列表，文件夹和文件
//
////        Log.i("SYD_OTA", "files L:" + files.length);
//
//        for (int i = 0; i < files.length; i++) {
//            File f = files[i];
//            if (f.isFile()) {
//                String f_name = f.getName();
//
//                if (f_name.indexOf(Extension) != -1) {
//                    //Log.i("SYD_OTA","files name:"+f_name);
//                    FileNameList.add(f_name);
//                    //Log.i("SYD_OTA", "name:" + f.getName() + "      "+"path:" + f.getPath());
//                }
//            }
//        }
//        FileNameList.add("tpm_22_12_20_v005.bin");
        FileNameList.add("");
    }

    void ShowVibrator(final Byte status) {
        Vibrator vibrator = (Vibrator) this.getSystemService(this.VIBRATOR_SERVICE);
        long[] patter = {1000, 1000, 2000, 100};
        vibrator.vibrate(patter, -1);   //0 循环 1不循环
    }

    void ShowStatus(final String status) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                Status_textView.setText(status);
            }
        });
    }

    void ShowUpdatefile(final String status) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                Update_textView.setText(status);
            }
        });
    }

    void ShowTarget_BirVer(final String status) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                Target_BirVer.setText(status);
            }
        });
    }

    void ShowOTA_Bin_BirVer(final String status) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                OTA_Bin_BirVer.setText(status);
            }
        });
    }

    void ShowStatusPercentage(final String status) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                StatusPercentage_textView.setText(status);
            }
        });
    }

    void Showelapsedtimer(final long second) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                elapsedtimer_textView.setText(Long.toString(second / 1000) + "." + Long.toString(second % 1000) + "S");
            }
        });
    }

    void ShowProgressBar(int mProgressStatus) {
        mprogressBarOta.setProgress(mProgressStatus);
    }

    void EnableButton(final Button bt, final Boolean IsEnable) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                bt.setEnabled(IsEnable);
            }
        });
    }

    void EnableListview(final ListView lv, final Boolean IsEnable) {
        runOnUiThread(new Runnable()   // 這個執行緒是為了 UI 畫面顯示
        {
            @Override
            public void run() {
                lv.setEnabled(IsEnable);
            }
        });
    }

    public void saveUserInfo(Context context, int otaversions, String key) {
        /**
         * SharedPreferences将用户的数据存储到该包下的shared_prefs/config.xml文件中，
         * 并且设置该文件的读取方式为私有，即只有该软件自身可以访问该文件
         */
        SharedPreferences sPreferences = context.getSharedPreferences("svae_config", context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sPreferences.edit();
        //当然sharepreference会对一些特殊的字符进行转义，使得读取的时候更加准确
        editor.putInt(key, otaversions);
        //这里我们输入一些特殊的字符来实验效果
//          editor.putString("specialtext", "hajsdh><?//");
//          editor.putBoolean("or", true);
//          editor.putInt("int", 47);
        //切记最后要使用commit方法将数据写入文件
        editor.commit();
    }


}
